package io.adrainty.bolee.framework.gateway.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import io.adrainty.bolee.framework.commons.basic.ResponseCode;
import io.adrainty.bolee.framework.gateway.utils.ResponseHelper;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <p>GatewayGlobalExceptionHandler</p>
 *
 * @author AdRainty
 * @version V1.0.0
 * @description 网关异常处理
 * @since 2025/7/30 11:46:38
 */

@Slf4j
public class GatewayGlobalExceptionHandler implements ErrorWebExceptionHandler {

    @NotNull
    @Override
    public Mono<Void> handle(@NotNull ServerWebExchange exchange, @NotNull Throwable ex) {
        log.error("Resolve response error: ", ex);

        if (ex instanceof NotLoginException) {
            return ResponseHelper.writeFailed(exchange.getResponse(), ResponseCode.USER_NOT_LOGIN, HttpStatus.UNAUTHORIZED);
        } else if (ex instanceof NotPermissionException) {
            return ResponseHelper.writeFailed(exchange.getResponse(), ResponseCode.USER_FORBIDDEN, HttpStatus.FORBIDDEN);
        } else if (ex instanceof RateLimitRequestException) {
            return ResponseHelper.writeFailed(exchange.getResponse(), ResponseCode.RETRY_LATER, HttpStatus.TOO_MANY_REQUESTS);
        } else if (ex instanceof NotFoundException) {
            return ResponseHelper.writeFailed(exchange.getResponse(), ResponseCode.SERVICE_NOT_AVAILABLE, HttpStatus.SERVICE_UNAVAILABLE);
        } else {
            return ResponseHelper.writeFailed(exchange.getResponse(), ResponseCode.UN_ERROR);
        }
    }
}
